import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/AgeSpan.dart';
import 'package:toys_flutter/components/AuthSpan.dart';
import 'package:toys_flutter/components/LevelSpan.dart';
import 'package:toys_flutter/components/MyImageWidget.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';
import 'package:toys_flutter/pages/UserDetail.dart';
import 'package:toys_flutter/store/app.dart';
import 'package:toys_flutter/utils/style_utils.dart';

class DynamicDetail extends StatefulWidget {
  final String id;
  const DynamicDetail({super.key, required this.id});

  @override
  State<DynamicDetail> createState() => _DynamicDetailState();
}

class _DynamicDetailState extends State<DynamicDetail> {
  // 动态
  Map<String, dynamic>? _dynamic;

  Future<void> _getData() async {
    var res = await Api.communityDetail({'id': widget.id});
    if (res['code'] == 1) {
      setState(() {
        _dynamic = res['data'];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('动态详情'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(10),
        child: RefreshableListView(
          onRefresh: () async {},
          children: [
            _buildUserInfo(context, _dynamic),
            // 其他动态项
            _buildRichText(context, _dynamic),
            // 图片
            _buildImages(context, _dynamic),
          ],
        ),
      ),
    );
  }
}

Widget _buildUserInfo(context, Map<String, dynamic>? item) {
  if (item == null || item['user'] == null) {
    return const SizedBox.shrink(); // 返回一个空的占位符
  }

  // 调用 AppState 的方法来获取用户数据
  final appState = Provider.of<AppState>(context, listen: false);
  final userInfo = appState.userInfo;
  final userId = userInfo['id'].toString() ?? '';

  final user = item['user'];
  final String avatarUrl = user['avatar'] ?? 'images/avatar.png';
  final String nickname = user['nickname'] ?? '未知';
  final String level = user['level']?.toString() ?? '1';
  final String gender = user['sex']?.toString() ?? '未知';
  final String age = user['age']?.toString() ?? '未知';

  return ListTile(
    contentPadding: const EdgeInsets.symmetric(horizontal: 0), // 设置左右内边距
    leading: InkWell(
      onTap: () {
        // 跳转到用户主页
        Get.to(UserDetail(userId: '1'));
      },
      child: TDAvatar(
        size: TDAvatarSize.medium,
        type: TDAvatarType.normal,
        avatarUrl: avatarUrl,
      ),
    ),
    title: Row(
      children: [
        Text(nickname),
        const SizedBox(width: 5),
        LevelSpan(level: level),
        const SizedBox(width: 5),
        const AuthSpan()
      ],
    ),
    subtitle: Row(
      children: [
        const SizedBox(
          height: 30,
        ),
        AgeSpan(gender: gender, age: age)
      ],
    ),
    trailing: userId != item['user_id']
        ? const Text('关注', style: StyleUtils.customTextStyle)
        : null,
  );
}

Widget _buildImages(BuildContext context, Map<String, dynamic>? item) {
  // 计算图片宽度
  final double imageWidth = (MediaQuery.of(context).size.width - 40) / 3;

  if (item == null || item['images'] == null) {
    return const SizedBox.shrink(); // 返回一个空的占位符
  }

  final List<String> images = (item['images'] as List<dynamic>)
      .map((v) => v['image'] as String)
      .toList();

  return Wrap(
    spacing: 10,
    runSpacing: 10,
    children: List.generate(images.length, (index) {
      final String image = images[index];

      return InkWell(
          onTap: () {
            // 在这里获取点击的索引
            TDImageViewer.showImageViewer(
              context: context,
              images: images,
              defaultIndex: index, // 传递点击的索引
            );
          },
          child: MyImageWidget(
            image: image,
            imageWidth: imageWidth,
          ));
    }),
  );
}

Widget _buildRichText(BuildContext context, Map<String, dynamic>? item) {
  if (item == null || item['user'] == null) {
    return const SizedBox.shrink(); // 返回一个空的占位符
  }

  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      RichText(
        text: TextSpan(
          text: item['content'],
          style: const TextStyle(fontSize: 15, color: Colors.black87),
        ),
      ),
      const SizedBox(height: 15),
      // 话题
      if (item['topic'] != null) TDTag(item['topic']['name']),
      const SizedBox(height: 15),
    ],
  );
}
